package com.qf.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.qf.pojo.DtsStorage;
import com.qf.service.StorageService;
import com.qf.util.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

@RestController
@CrossOrigin("*")
@RequestMapping("/storage")
public class StorageController {
    private static final Logger Logger= LoggerFactory.getLogger(StorageController.class);

    @Autowired
    private StorageService storageService;

    /**
     * 对象存储分页查询
     * @param page 当前页
     * @param limit 每页显示条数
     * @param key 文件的key
     * @param name  文件名
     * @param sort  排序字段
     * @param order 排序方式asc或者desc
     * @return
     */
    @RequestMapping("/list")
    public Object list(Integer page,Integer limit,String key,String name,String sort,String order){
        IPage<DtsStorage> iPage = storageService.findByPage(page, limit, key, name, sort, order);

        //封装返回的数据
        Map<String,Object> data = new HashMap<>();
        data.put("total", iPage.getTotal());
        data.put("items", iPage.getRecords());

        return ResponseUtil.ok(data);
    }

    /**
     * 文件上传对接阿里OSS
     * @param file
     * @return
     */
    @RequestMapping("/create")
    public Object create(@RequestParam("file") MultipartFile file) throws Exception{

        //1.获取文件名
        String originalFilename = file.getOriginalFilename();
        if (StringUtils.isEmpty(originalFilename)){
            throw new RuntimeException("上传文件为空，不允许上传！");
        }

        //2,获取文件拓展名
        String ext = originalFilename.substring(originalFilename.lastIndexOf("."));

        //3.调用service完成上传和存储
        DtsStorage storage = storageService.add(originalFilename, ext, (int) file.getSize(), file.getBytes());

        return ResponseUtil.ok(storage);
    }

    /**
     * 更新文件
     * @param storage
     * @return
     */
    @RequestMapping("/update")
    public Object update(@RequestBody DtsStorage storage){
        if (storageService.update(storage) == 0){
            Logger.info("系统管理->对象存储->编辑 错误:{}","更新数据失败！");
            return ResponseUtil.updatedDataFailed();
        }

        return ResponseUtil.ok(storage);
    }

    @RequestMapping("/delete")
    public Object delete(@RequestBody DtsStorage dtsStorage){
        String key = dtsStorage.getKey();
        if (StringUtils.isEmpty(key)){
            return ResponseUtil.badArgument();
        }
        storageService.deleteByKey(dtsStorage);

        return ResponseUtil.ok();
    }
}
